package mobi.weq.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mobi.weq.dao.UserDao;
import mobi.weq.model.User;

public class LoginServlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		User user = null;
		if (username != null && password != null) {
			UserDao ud = new UserDao();
			try {
				user = ud.getUserByUsernamePassword(username, password);
				HttpSession session = req.getSession(true);
				session.setAttribute("user", user);

			} catch (SQLException e) {
				System.out.println(e);
			}
		}

		if (user != null) {
			resp.sendRedirect("home");
		} else {
			req.setAttribute("errorMessage", "Wrong username/password");
			req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
		}
	}
}
